import { userList } from '../db/testmodel.js';
import User from '../model/User.js';
import url from 'url';
import moment from "moment"

async function test(ctx, next) {
	// ctx.body = `<h1>首页</h1>`
	// select all user
	// const userList = await User.findAll();
	// console.log(users.every(user => user instanceof User)); // true
	// console.log("All users:", JSON.stringify(users, null, 2));
	ctx.render('Users.html')
}

async function getusers(ctx, next) {

	{// const Urlp = url.parse(ctx.url, true); 		// 拿到页码和每页展示数
	// console.log(Urlp);

	// const page = Urlp.query.page || 1;		// Initialize page
	// const limit = Urlp.query.limit || 5; 	// default Show page
	// const totalPages = Math.ceil(userList.length / limit);	// All page
	// const newuserList = User.findAll();	// Create newarrlist to retrun page
	// for (let numpage = 0; numpage < totalPages; numpage++) {
	// 	let newarrlist

	// }

	// // 判断请求数值是否有效
	// if (page <= totalPages && limit <= userList.length) {
	// 	const nowIndex = (page - 1) * limit;		// START
	// 	let maxIndex = +nowIndex + +limit;		// END

	// 	if (maxIndex > userList.length) {		// constraint length for userList 
	// 		maxIndex = userList.length;
	// 	}

	// 	for (let i = nowIndex; i < maxIndex; i++) {		// retrun userlist
	// 		newuserList.push(userList[i]);
	// 	}

	// } else {
	// 	for (let i = 0; i < 5; i++) {		// Show first to fifth
	// 		newuserList.push(userList[i]);
	// 	}

	// 	ctx.redirect(`/userList?page=1&limit=5`);		// Redirect
	// }
	}

	const users = await User.findAll();


	users.forEach(user => {
		user.dataValues.registrationTime = (moment(user.registrationTime).format("YYYY-MM-DD HH:mm:ss"));
	});

	ctx.render("Users.html", { users });	//Userinfo render

}

async function userById(ctx, next) {
	const inid = ctx.params.id;
	// console.log(inid);

	if (inid === '0') {
		ctx.render("adAndUp.html")
	} else {
		const useron = await User.findByPk(inid);
		ctx.render("Users.html")
	}

}

async function insertuser(ctx, next) {
	const usercbj = ctx.request.body

	console.log(usercbj);

	// Create User
	await User.create(usercbj);

	ctx.status = 200;
	ctx.body = "新增成功";
}

async function updateuser(ctx, next) {
	const usercbj = ctx.request.body

	console.log(usercbj);

	// Create User
	await User.update(usercbj);

	ctx.status = 200;
	ctx.body = "修改成功";
	
	ctx.render("adAndUp.html");
}

async function deleteuser(ctx, next) {
	const id = ctx.params.id;

	const isOk = await User.findByPk(id);

	if (!isOk) {
		console.log("用户不存在");

	} else {
		await User.destroy({ where: { id } })

		ctx.status = 200;
		ctx.body = "删除成功";
	}
}


export const object = {
	"get@/": test,
	"get@/users": getusers,
	"get@/users/:id": userById,
	"post@/users": insertuser,
	"put@/users/:id": updateuser,
	"delete@/users/:id": deleteuser,
};